package com.jia.leetcode2.string;

/**
 * @program: designPattern
 * @description:
 * @author: STU756
 * @create: 2021-03-25 14:02
 */
public class ReverseWords {
    /**
     * Reverse words in a string
     * 单词前后没有空格，单词之间有空格
     * @param s
     * @return
     */
    public String reverseWords(String s){
        StringBuilder resversed  = new StringBuilder();
        for(int i = s.length() -1, j = s.length(); i >= 0; i--) {
            if (s.charAt(i) == ' ') {
                j = i;
            } else if (i == 0 || s.charAt(i - 1) == ' ') {
                //reversed判断前面是否有一个单词，如果有就用空格隔开，没有的话就不需要
                if (resversed.length() != 0) {
                    resversed.append(' ');
                }
                resversed.append(s.substring(i, j));
            }
        }
        return resversed.toString();
    }
    public String reverseWords2(String s){
        StringBuilder resversed  = new StringBuilder();
        for(int i = s.length() -1, j = s.length(); i >= 0; i--) {
            if(s.charAt(i) == ' '){
               if(i + 1 < j) {
                    //需要翻转[i+1 ~ j]
                    resversed.append(s.substring(i + 1, j));
                }
                j = i;
                resversed.append(' ');
            }else if(i == 0){
                resversed.append(s.substring(i, j));
            }
        }
        return resversed.toString();
    }

    public static void main(String[] args) {
        String s = "  the  sky is  blue ";
        ReverseWords reverseWords = new ReverseWords();
        System.out.println(reverseWords.reverseWords(s));
    }
}
